import foundation
import json
from code_sync import SourceCode, IPADownload


def init_mimi_project(db_path, project_dir):
    """
    mimi项目初始化
    :return:
    """
    app_path = db_path

    #创建表
    create_app_table_sql = """
            CREATE TABLE IF NOT EXISTS app (
            app_name TEXT PRIMARY KEY,
            code_source TEXT,
            ipa_download TEXT,
            project_dir TEXT
        );
        """
    foundation.sqlite.excute_sqlite(app_path, create_app_table_sql)

    #插入项目配置
    insert_row_sql = """
            insert into app (app_name, code_source, ipa_download, project_dir) values (?, ?, ?, ?);
        """

    SourceCode.project_dir = project_dir

    source_codes = [
        SourceCode(remote_url="git@182.92.161.213:mimi/ios/MMVoice.git",
                   branch="dev",
                   item_name="MMVoice").__dict__,
        SourceCode(remote_url="git@182.92.161.213:mimi/ios/MMFoundationModule.git",
                   branch="dev",
                   item_name="MMFoundationModule").__dict__,
        SourceCode(remote_url="git@182.92.161.213:mimi/ios/MMIMModule.git",
                   branch="dev",
                   item_name="MMIMModule").__dict__
    ]
    str_code = json.dumps(source_codes)

    ipa_download = IPADownload(manifest_url="https://app-distribution-1310744949.cos.ap-shanghai.myqcloud.com/mimi-ios/mimi_manifest_m2.plist")
    ipa_str = json.dumps(ipa_download.__dict__)

    foundation.sqlite.excute_sqlite(app_path, insert_row_sql, params=["mimi", str_code, ipa_str, project_dir])

def get_mimi_project(db_path):
    """
    查询mimi配置
    :return:
    """
    app_path = db_path
    query_mimi_sql = """
                select * from app where app_name='mimi';
            """

    result = foundation.sqlite.query_sqlite(app_path, query_mimi_sql)

    SourceCode.project_dir = result[0][3]

    source_codes = result[0][1]
    arr = json.loads(source_codes)
    for item in arr:
        source_code = SourceCode(remote_url=item["remote_url"], branch=item["branch"],
                                 item_name=item["item_name"])
        print(source_code)
        print(source_code.project_dir)
        source_code.sync_code()


if __name__ == "__main__":
    db_path = "app.db"
    init_mimi_project(db_path, project_dir="/Users/mac/Documents/mowan/project/MiMiVoice")
    get_mimi_project(db_path)

    pass